﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RecordManager : MonoBehaviour
{
    static RecordManager instance;

    public GameObject recordPanl, recordPrefab;
    public RecordList victoryRecordList;

    List<GameObject> recordList = new List<GameObject>();//用于添加RecordPrefab的列表

    private void Awake()
    {
        if (instance!=null)
        {
            Destroy(gameObject);
            return;
        }
        instance = this;
    }


    public static void RefreshRecordList()//刷新记录列表排名
    {
        for (int i = 0; i < instance.recordPanl.transform.childCount; i++)
        {
            if (instance.recordPanl.transform.childCount == 0) break;
            
            Destroy(instance.recordPanl.transform.GetChild(i).gameObject);
            instance.recordList.Clear();
        }

        SortList();

        for (int i = 0; i < 5; i++)
        {
            if (instance.victoryRecordList.recordList[i] == null)
                return;

            instance.recordList.Add(Instantiate(instance.recordPrefab));
            instance.recordList[i].transform.SetParent(instance.recordPanl.transform);
            instance.recordList[i].GetComponent<RecordPrefab>().SetupRecordPrefab(instance.victoryRecordList.recordList[i], i);
        }

    }

    public static void SortList()//对记录列表冒泡排序
    {

        List<PlayerData> rl = instance.victoryRecordList.recordList;

        for (int i = 0; i < rl.Count - 1; i++)
        {
            for (int j = 0; j < rl.Count - 1 - i; j++)
            {
                if (rl[j] == null || rl[j + 1] == null)
                    continue;

                if (rl[j].playerRecord > rl[j + 1].playerRecord)
                {
                    float temp = rl[j].playerRecord;
                    string st = rl[j].playerName;
                    rl[j].playerRecord = rl[j + 1].playerRecord;
                    rl[j].playerName = rl[j + 1].playerName;
                    rl[j + 1].playerRecord = temp;
                    rl[j + 1].playerName = st;
                }
            }
        }
        for (int i = 0; i < rl.Count; i++)
        {
            if (i > 6)
                rl[i] = null;
        }
        /*foreach (var pd in TestList.GetPlayerDataList())
        {
            Debug.Log(pd + "Data的值");
            if (pd == null)
                return;

            int min = (int)(pd.playerRecord / 60);
            float sec = pd.playerRecord % 60;

            string record = min.ToString("00") + " : " + sec.ToString("00");
            Debug.Log(pd.playerName + " 的记录: " + record);
        }*/
    }
}
